﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using CoreShop.App;
using CoreShop.Library;
using CoreShop.Services;
using System.Windows.Forms;
using CoreShop.Model;
using CoreShop.PrintService;
using SqlSugar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Rebar;
using Yitter.IdGenerator;
using SqlSugar.Extensions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Sunny.UI;
using System.Xml;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using CoreShop.Model.UI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using static System.Windows.Forms.AxHost;
using Sunny.UI.Win32;
using IWshRuntimeLibrary;
using FastMember;
using PluSoft.Utils;
using System.Threading.Tasks;
using CoreShop.Model.FromBody;
using Org.BouncyCastle.Asn1.Tsp;
using CoreShop.Model.OrderModels;
using static CoreShop.Library.GlobalEnumVars;
using System.Diagnostics.Metrics;
using MySqlX.XDevAPI.Relational;
using System.Data.SqlTypes;
using static CoreShop.App.ActivitieUtil;
using CoreShop.App.Units.Interface;

namespace CoreShop.App
{
    public class MallOrderUtil
    {
        /// <summary>
        /// 获取在线订单数量
        /// </summary>
        /// <param name="food"></param>
        /// <returns></returns>
        public int LoadOrderNum(corecmsexchange exchange)
        {
            var posRmo = new PosRemoteServices(AppConstVars.sysUser.ccessToken);
            ReturnModel returnModel1 = posRmo.GetOrderListXcx(AppConstVars.sysStore, AppConstVars.sysUser, exchange);
            if (returnModel1.Status != ReturnStatus.Success)
            {
                //LogManage.Info($"获取在线订单失败！{returnModel1.MessageOrString}");
                return 0;
            }
            ReturnApiModel<OnlineOrderModel> returnApiMode = returnModel1.MessageOrString.JsonToEntity<ReturnApiModel<OnlineOrderModel>>();

            if (returnApiMode.code != "200")
            {
                //LogManage.Info($"获取在线订单失败！{returnApiMode.msg}");
                return 0;
            }

            List<OnlineOrderModel> returnOnlineOrder = returnApiMode.rows;
            int DataCount = !string.IsNullOrEmpty(returnApiMode.total) ? Convert.ToInt32(returnApiMode.total) : 0;
            SetOrderMaster(returnOnlineOrder, exchange);//保存订单到本地
            return DataCount;
        }

        /// <summary>
        /// 保存订单到本地
        /// </summary>
        public void SetOrderMaster(List<OnlineOrderModel> returnOnlineOrder, corecmsexchange exchange)
        {
            if ((returnOnlineOrder == null) || (returnOnlineOrder.Count == 0)) return;
            try
            {
                DateTime createTime = exchange.mallOrderTime;
                List<corecmsordermaster> orders = new List<corecmsordermaster>();
                foreach (var item in returnOnlineOrder)
                {
                    if (item.createTime > createTime) createTime = CommFunc.ConvertToDateTime(item.createTime);
                    if (item.updateTime > createTime) createTime = CommFunc.ConvertToDateTime(item.updateTime);
                    if (item.payTime > createTime) createTime = CommFunc.ConvertToDateTime(item.payTime);
                    string strMaster = JsonConvert.SerializeObject(item);
                    corecmsordermaster orderMaster = JsonConvert.DeserializeObject<corecmsordermaster>(strMaster);
                    orderMaster.id = CommFunc.GetCorpNextId(AppConstVars.sysUser.corpId, YitIdHelper.NextId());
                    orderMaster.content = strMaster;
                    orderMaster.tenantId = AppConstVars.sysStore.corpId;
                    orderMaster.checkFlag = false;
                    orderMaster.isUpload = false;
                    orders.Add(orderMaster);
                }
                if ((orders != null) && (orders.Count > 0))
                {                    
                    new corecmsordermasterServices().InsertOrUpdate(orders);

                    new corecmsexchangeServices().Update(a => new corecmsexchange()
                    {
                        mallOrderTime = CommFunc.ConvertToDateTime(createTime).AddSeconds(1)
                    }, a => a.storeId == exchange.storeId);

                    if (AppConstVars.systemsetup.orderPlaySound > 0) 
                    {
                        string mstr = "您有新的订单，请注意查收.";
                        SoundHelper.SoundPlayer(mstr);
                    }
                }
            }
            catch (Exception ex) { }
        }

        /// <summary>
        /// 保存订单到本地
        /// </summary>
        public static int GetOrderCount()
        {            
            try
            {
               return new corecmsordermasterServices().AsQueryable().Where(p=>p.checkFlag == false).Count();
            }
            catch (Exception ex) { }
            return 0;
        }

        public static PosOrderHeadDto CreateTopUpOnlineOrder(OnlineOrderModel OnlineOrderInfo, long masterId)
        {
            string sDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //主要信息
            PosOrderHeadDto posOrderHeadDto = new PosOrderHeadDto();
            posOrderHeadDto.posOrderHeadId = OnlineOrderInfo.id.ToString();
            posOrderHeadDto.amountBalance = OnlineOrderInfo.payAmount.ObjToDecimal();
            posOrderHeadDto.amountDiscount = OnlineOrderInfo.payAmount.ObjToDecimal();
            posOrderHeadDto.amountOrder = OnlineOrderInfo.totalAmount.ObjToDecimal(0);
            posOrderHeadDto.amountFact = OnlineOrderInfo.FreeAmount.ObjToDecimal(0);
            posOrderHeadDto.auditer = AppConstVars.sysUser.userName;
            //HeadOrderInfo.billBal = billBal;
            posOrderHeadDto.billDate = sDateTime;
            //HeadOrderInfo.billLine = billLine;
            posOrderHeadDto.billNo = OnlineOrderInfo.orderSn;
            posOrderHeadDto.branchId = AppConstVars.sysStore.branchId.ToString();
            posOrderHeadDto.billTime = sDateTime;
            posOrderHeadDto.orderBillTypeId = ((int)GlobalEnumVars.OrderBillType.Order).ToString();
            posOrderHeadDto.orderId = masterId.ToString();
            posOrderHeadDto.orderTypeId = "1";
            posOrderHeadDto.saleTypeId = GlobalEnumVars.SaleType.线上.GetHashCode().ToString();
            posOrderHeadDto.pickType = "1";
            posOrderHeadDto.saleSortId = "1";
            posOrderHeadDto.status = "5";
            posOrderHeadDto.warehouseId = AppConstVars.sysStore.id.ToString();
            //HeadOrderInfo.billPromo = billPromoList;
            posOrderHeadDto.sourceNo = OnlineOrderInfo.orderSn;
            posOrderHeadDto.branchName = AppConstVars.sysStore.branchName.ToString();
            posOrderHeadDto.dutycode = AppConstVars.classNumber;
            posOrderHeadDto.tenantId = AppConstVars.sysStore.corpId.ToString();
            return posOrderHeadDto;
        }

        /// <summary>
        /// 创建在线支付信息
        /// </summary>
        /// <param name="cashDecimal"></param>
        /// <param name="discontZero">商家优惠，抹零</param>
        /// <returns></returns>
        public static PosOrderBalDto CreateCashOnlineOder(decimal cashDecimal, string baseBalanceTypeId, string paySn, decimal amountFact = 0, string dispatchingType = null)
        {
            PosOrderBalDto posOrderBalDto = new PosOrderBalDto();
            posOrderBalDto.Id = CommFunc.GetCorpNextId(AppConstVars.sysUser.corpId,YitIdHelper.NextId());
            posOrderBalDto.baseBalanceTypeId = baseBalanceTypeId;
            posOrderBalDto.amountPayment = cashDecimal;
            posOrderBalDto.amountDiscount = cashDecimal;
            posOrderBalDto.amountFact = amountFact;
            posOrderBalDto.accountCode = string.Empty;
            posOrderBalDto.paymentSn = paySn;// string.Empty.GetMchNo();
            posOrderBalDto.status = PayStatus.成功.GetHashCode().ToString();
            posOrderBalDto.freightSort = dispatchingType;

            return posOrderBalDto;
        }


        /// <summary>
        /// 得到订单下的商品信息
        /// </summary>
        /// <param name="tableid"></param>
        /// <returns></returns>
        public async static Task<bool> SetUpLoadOrderDataAsync(long masterId)
        {
            var masterServices = new corecmsfoodordermasterServices();
            var postData = await MallOrderUtil.GetUpLoadOrderDataAsync(masterId);
            if (postData == null) return true;
            var res = await OrderApiUtil.SendOrderAsync(postData);
            if ((res != null) && (res.code == 200))
            {
                return new corecmsordermasterServices().Update(a => new corecmsordermaster()
                {
                    isUpload = true
                }, a => a.id == masterId);
            }
            return false;
        }

        /// <summary>
        /// 得到订单下的商品信息
        /// </summary>
        /// <param name="tableid"></param>
        /// <returns></returns>
        public async static Task<PosOrderHeadDto> GetUpLoadOrderDataAsync(long masterId)
        {
            try
            {
                var orderMaster = new corecmsordermasterServices().GetById(masterId);
                if ((orderMaster == null) || (!orderMaster.checkFlag)) return null;                
                OnlineOrderModel OnlineOrderInfo = orderMaster.content.JsonToEntity<OnlineOrderModel>();
                PosOrderHeadDto HeadOrderInfo = CreateTopUpOnlineOrder(OnlineOrderInfo, masterId);

                //付款信息
                List<PosOrderBalDto> posOrderBalDtos = new List<PosOrderBalDto>();
                PosOrderBalDto posOrderBalDto = CreateCashOnlineOder(OnlineOrderInfo.totalAmount.ObjToDecimal(0), OnlineOrderInfo.balanceTypeId, OnlineOrderInfo.PaySn, OnlineOrderInfo.payAmount.ObjToDecimal(0), OnlineOrderInfo.DispatchingType);
                posOrderBalDto.orderId = HeadOrderInfo.orderId;
                posOrderBalDtos.Add(posOrderBalDto);
                HeadOrderInfo.billBal = posOrderBalDtos;

                //商品信息
                List<PosOrderLineDto> posOrderLineDtos = new List<PosOrderLineDto>();
                foreach (var item in OnlineOrderInfo.XcxOrderItem)
                {
                    PosOrderLineDto posOrderLineDto = new PosOrderLineDto();
                    posOrderLineDto.Id = CommFunc.GetCorpNextId(AppConstVars.sysUser.corpId, YitIdHelper.NextId());
                    posOrderLineDto.spuId = item.spuId;
                    posOrderLineDto.qtyOrder = item.num.ToDecimal();
                    posOrderLineDto.priceOrder = item.SourcePrice.ObjToDecimal(0);
                    posOrderLineDto.priceDiscount = (item.ShareAmount / item.num.ObjToDecimal(0)).ObjToDecimal();
                    posOrderLineDto.priceBalance = (item.ShareAmount / item.num.ToDecimal()).ObjToDecimal();
                    posOrderLineDto.priceCost = item.SourcePrice.ObjToDecimal();
                    posOrderLineDto.amountOrder = item.salePrice.ObjToDecimal();
                    posOrderLineDto.amountDiscount = item.ShareAmount.ObjToDecimal();
                    posOrderLineDto.amountBalance = item.ShareAmount.ObjToDecimal();
                    posOrderLineDto.amountCost = item.SourcePrice.ObjToDecimal() * item.num.ObjToDecimal();
                    posOrderLineDto.amountZ = 0;
                    posOrderLineDto.status = "1";
                    posOrderLineDto.spuCode = item.spuCode;
                    posOrderLineDto.spuName = item.itemName;
                    posOrderLineDto.pdtSpuSpecId = item.specId;
                    posOrderLineDto.orderId = HeadOrderInfo.orderId;
                    posOrderLineDto.warehouseId = AppConstVars.sysUser.storeId.ToString();
                    posOrderLineDtos.Add(posOrderLineDto);
                }
                HeadOrderInfo.billLine = posOrderLineDtos;

                return HeadOrderInfo;
            }
            catch (Exception ex)
            {
                await new corecmsprinttasklogServices().InsertAsync("订单转换:" + ex.Message);
                return null;
            }
        }

    }
}
